package com.mijie.homi.api;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.mijie.core.Status;
import com.mijie.exception.PermissionDeniedException;
import com.mijie.exception.RecordNotFoundException;
import com.mijie.homi.common.constant.HomiConstants;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.domain.commom.Comment;
import com.mijie.homi.domain.commom.Reply;
import com.mijie.homi.domain.commom.Review;
import com.mijie.homi.service.album.AlbumService;
import com.mijie.homi.service.common.CommentService;
import com.mijie.homi.service.common.CommentService.COMMENT;
import com.mijie.homi.service.common.EventService;
import com.mijie.homi.service.common.ReplyService;
import com.mijie.homi.service.common.ReplyService.REPLY;
import com.mijie.homi.service.mood.MoodService;
import com.mijie.homi.service.topic.TopicService;
import com.mijie.homi.service.user.UserService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.IOUtil;

public class CommomApi {

	@Autowired
	private CommentService commentService;
	@Autowired
	private ReplyService replyService;
	@Autowired
	private UserService userService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private MoodService moodService;
	@Autowired
	private AlbumService albumService;
	
	private Logger logger = Logger.getLogger(CommomApi.class);
	
	public void postComment(Enum<COMMENT> type,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		Integer userId = ServerHelper.getUserId(request);
		JSONObject json = JSONObject.fromObject(content);
		int topicId = -1;
		if(type.equals(COMMENT.TOPIC_OPINION)){
			topicId = json.getInt("topicId");
			json.remove("topicId");
		}
		
		Comment comment = (Comment) JSONObject.toBean(json,Comment.class);
		if(comment.getContent()==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		comment.setContent(ServerHelper.filterSensitiveWord(comment.getContent().trim()));
		if(comment.getContent().length()>HomiConstants.MAX_WORD_COMMENT){
			status.setCode(HomiStatusCode.CONTENT_LENGTH_LIMIT);
			status.write();
			return;
		}
		
		comment.setReviewer(userId);
		Review review = new Review();
		review.setEventId(comment.getTargetId());
		review.setReceiver(comment.getReceiver());
		review.setReviewer(comment.getReviewer());
		review.setContent(comment.getContent());
		review.setCreateAt(new Date());
		EventService eventService = null;
		if(type.equals(COMMENT.PHOTO)){
			eventService = this.albumService;
		}else if (type.equals(COMMENT.MOOD)){
			eventService = this.moodService;
		}if (type.equals(COMMENT.TOPIC_OPINION)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.newReview(review);
			if(rows>0){
				//保存一份数据到旧表
				comment.setReviewId(review.getId());
				comment.setCreateAt(review.getCreateAt());
				commentService.postComment(type,comment);
			}
		} catch (RecordNotFoundException e) {
			e.printStackTrace();
		};
		
		if(rows==0){
			status.setCode(HomiStatusCode.API_EXCEPTION);
		}else{
			status.setResult("{\"id\":"+comment.getId()+"}");
		}
		status.write();
	}
	
	public void listComment(Enum<COMMENT> type,long idx,long targetId,int limit,
			HttpServletRequest request,HttpServletResponse response){
		List<Comment> list = commentService.listComment(type,idx, targetId, limit);
		JSONArray result = new JSONArray();
		JSONObject commentJson = null;
		JSONArray replyJsonArray = null;
		JSONObject replyJson = null;
		List<Reply> replyList = null;
		User reviewer = null;
		User sender = null;
		User receiver = null;
		Comment comment = null;
		Reply reply = null;
		Iterator<Comment> commentIter = list.iterator();
		Iterator<Reply> replyIter = null;
		while(commentIter.hasNext()){
			comment = commentIter.next();
			commentIter.remove();
			commentJson = JSONObject.fromObject(comment);
			commentJson.remove("tableName");
			commentJson.put("createAt", comment.getCreateAt().getTime());
			commentJson.put("reviewerNickName", "无名");
			commentJson.put("reviewerAvatar", "");
			commentJson.put("reviewerGender", 1);
			reviewer = userService.getUserById(comment.getReviewer());
			if(reviewer!=null){
				commentJson.put("reviewerGender", reviewer.getGender());
				commentJson.put("reviewerNickName", reviewer.getNickName());
				commentJson.put("reviewerAvatar", HomiUtil.getRealUrl(reviewer.getAvatar()));
			}
			
			
			replyList = replyService.listReplyByTargetIds(type, comment.getId(), 3);
			replyJsonArray = new JSONArray();
			replyIter = replyList.iterator();
			while(replyIter.hasNext()){
				reply = replyIter.next();
				replyIter.remove();
				replyJson = JSONObject.fromObject(reply);
				replyJson.remove("tableName");
				receiver = userService.getUserById(reply.getReceiver());
				replyJson.put("receiverNickName", receiver==null?"无名":receiver.getNickName());
				replyJson.put("senderNickName", "无名");
				replyJson.put("senderAvatar", "");
				
				sender = userService.getUserById(reply.getSender());
				if(sender!=null){
					replyJson.put("senderNickName", sender.getNickName());
					replyJson.put("senderAvatar", HomiUtil.getRealUrl(sender.getAvatar()));
				}
				replyJson.put("createAt", reply.getCreateAt().getTime());
				replyJsonArray.add(replyJson.toString());
			}
			commentJson.accumulate("replys", replyJsonArray);
			result.add(commentJson.toString());
		}
		replyIter = null;
		replyList = null;
		commentIter = null;
		list = null;
		Status status = new Status(request,response);
		status.setResult(result);
		status.write();
	}
	
	public void deleteComment(Enum<COMMENT> type,long id,long parentId,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		Integer reviewer = ServerHelper.getUserId(request);
		Comment comment = commentService.getCommentById(CommentService.commentTableMap.get(type), id);
		EventService eventService = null;
		if(type.equals(COMMENT.PHOTO)){
			eventService = this.albumService;
		}else if (type.equals(COMMENT.MOOD)){
			eventService = this.moodService;
		}if (type.equals(COMMENT.TOPIC_OPINION)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.deleteReview(parentId, comment.getReviewId(), reviewer);
			if(rows>0)
				commentService.deleteComment(type, reviewer, id,parentId);
		} catch (RecordNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (PermissionDeniedException e) {
			logger.error(e.getMessage(), e);
		};
		
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.POSSESSION_ERROR);
		status.write();
	}
	
	public void deleteCommentByAdmin(Enum<COMMENT> type,long id,long parentId,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		Integer userId = ServerHelper.getUserId(request);
		Comment comment = commentService.getCommentById(CommentService.commentTableMap.get(type), id);
		EventService eventService = null;
		if(type.equals(COMMENT.PHOTO)){
			eventService = this.albumService;
		}else if (type.equals(COMMENT.MOOD)){
			eventService = this.moodService;
		}if (type.equals(COMMENT.TOPIC_OPINION)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.deleteReview(parentId, comment.getReviewId(), userId);
			if(rows>0)
				commentService.deleteCommentByAdmin(type, userId, id,parentId);
		} catch (RecordNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (PermissionDeniedException e) {
			logger.error(e.getMessage(), e);
		};
		
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.POSSESSION_ERROR);
		status.write();
	}
	
	public void postReply(Enum<REPLY> type,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		Integer userId = ServerHelper.getUserId(request);
		JSONObject json = JSONObject.fromObject(content);
		Reply reply = (Reply) JSONObject.toBean(json,Reply.class);
		if(reply.getContent()==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		reply.setContent(ServerHelper.filterSensitiveWord(reply.getContent().trim()));
		if(reply.getContent().length()>HomiConstants.MAX_WORD_REPLY){
			status.setCode(HomiStatusCode.CONTENT_LENGTH_LIMIT);
			status.write();
			return;
		}
		
		reply.setSender(userId);
		
		Comment comment = commentService.getCommentById(type, reply.getTargetId());
		Review review = new Review();
		review.setReferId(comment.getReviewId());
		review.setEventId(comment.getTargetId());
		review.setReceiver(reply.getReceiver());
		review.setReviewer(reply.getSender());
		review.setContent(reply.getContent());
		review.setCreateAt(new Date());
		review.setParentId(reply.getParentId());
		
		EventService eventService = null;
		if(type.equals(REPLY.PHOTO_COMMENT)){
			eventService = this.albumService;
		}else if (type.equals(REPLY.MOOD_COMMENT)){
			eventService = this.moodService;
		}if (type.equals(REPLY.TOPIC_OPINION_COMMENT)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.newReview(review);
			if(rows>0){
				//保存一份数据到旧表
				reply.setReviewId(review.getId());
				reply.setCreateAt(review.getCreateAt());
				replyService.postReply(type,reply);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		};
		
		if(rows==0)
			status.setCode(HomiStatusCode.API_EXCEPTION);
		else
			status.setResult("{\"id\":\""+reply.getId()+"\"}");
		status.write();
	}
	
	public void deleteReply(Enum<REPLY> type,long id,long parentId,
			HttpServletRequest request,HttpServletResponse response){
		int sender = ServerHelper.getUserId(request);
		Reply reply = replyService.getReplyById(type, id);
		EventService eventService = null;
		if(type.equals(REPLY.PHOTO_COMMENT)){
			eventService = this.albumService;
		}else if (type.equals(REPLY.MOOD_COMMENT)){
			eventService = this.moodService;
		}if (type.equals(REPLY.TOPIC_OPINION_COMMENT)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.deleteReview(parentId, reply.getReviewId(), sender);
			if(rows>0)
				replyService.deleteReply(type, sender, id,parentId);
		} catch (RecordNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (PermissionDeniedException e) {
			logger.error(e.getMessage(), e);
		}
		
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.POSSESSION_ERROR);
		status.write();
	}
	
	public void deleteReplyByAdmin(Enum<REPLY> type,long id,long parentId,
			HttpServletRequest request,HttpServletResponse response){
		int userId = ServerHelper.getUserId(request);
		Reply reply = replyService.getReplyById(type, id);
		EventService eventService = null;
		if(type.equals(REPLY.PHOTO_COMMENT)){
			eventService = this.albumService;
		}else if (type.equals(REPLY.MOOD_COMMENT)){
			eventService = this.moodService;
		}if (type.equals(REPLY.TOPIC_OPINION_COMMENT)){
			eventService = this.topicService;
		}
		
		int rows = 0;
		try {
			rows = eventService.deleteReview(parentId, reply.getReviewId(), userId);
			if(rows>0)
				replyService.deleteReplyByAdmin(type, userId, id,parentId);
		} catch (RecordNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (PermissionDeniedException e) {
			logger.error(e.getMessage(), e);
		}
		
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.POSSESSION_ERROR);
		status.write();
	}
	
	public void listReply(Enum<REPLY> type,long idx,long targetId,int limit,
			HttpServletRequest request,HttpServletResponse response){
		List<Reply> list = replyService.listReply(type,idx, targetId, limit);
		JSONArray result = new JSONArray();
		JSONObject json = null;
		User sender = null;
		User receiver = null;
		Reply reply = null;
		Iterator<Reply> iter = list.iterator();
		while(iter.hasNext()){
			reply = iter.next();
			iter.remove();
			json = JSONObject.fromObject(reply);
			json.remove("tableName");
			sender = userService.getUserById(reply.getSender());
			receiver = userService.getUserById(reply.getReceiver());
			json.put("receiverNickName", receiver==null?"无名":receiver.getNickName());
			json.put("senderNickName", "无名");
			json.put("senderAvatar", "");
			json.put("commentId", targetId);
			if(sender!=null){
				json.put("senderNickName", sender.getNickName());
				json.put("senderAvatar", HomiUtil.getRealUrl(sender.getAvatar()));
			}
			
				
			json.put("createAt", reply.getCreateAt().getTime());
			result.add(json.toString());
		}
		iter = null;
		list = null;
		Status status = new Status(request,response);
		status.setResult(result);
		status.write();
	}
	
	public void review(EventService delegate,HttpServletRequest request,HttpServletResponse response) {
		Status status = new Status(request,response);
		String content = null;
		try {
			content = IOUtil.getContent4InputStream(request.getInputStream());
		} catch (IOException e) {
			status.setCode(HomiStatusCode.API_EXCEPTION);
			status.write();
			return;
		}
		
		JSONObject json = JSONObject.fromObject(content);
		Review review = (Review) JSONObject.toBean(json, Review.class);
		if(review.getContent()==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		review.setContent(ServerHelper.filterSensitiveWord(review.getContent().trim()));
		if(review.getContent().length()>HomiConstants.MAX_WORD_COMMENT){
			status.setCode(HomiStatusCode.CONTENT_LENGTH_LIMIT);
			status.write();
			return;
		}
		review.setReviewer(ServerHelper.getUserId(request));
		try {
			int succ = delegate.newReview(review);
			if(succ==0) status.setCode(HomiStatusCode.API_EXCEPTION);
			else{
				//保存一份数据到旧表
				if(review.getReferId()==0){
					//对应旧版的评论
					Comment comment = new Comment();
					comment.setReviewId(review.getId());
					comment.setCreateAt(review.getCreateAt());
					comment.setReceiver(review.getReceiver());
					comment.setReviewer(review.getReviewer());
					comment.setContent(review.getContent());
					comment.setTargetId(review.getEventId());
					
					COMMENT type = null;
					if(delegate instanceof TopicService){
						type = COMMENT.TOPIC_OPINION;
					}else if(delegate instanceof MoodService){
						type = COMMENT.MOOD;
					}else if(delegate instanceof AlbumService){
						type = COMMENT.PHOTO;
					}
					commentService.postComment(type, comment);
				}
			}
		} catch (RecordNotFoundException e) {
			status.setCode(HomiStatusCode.RECORD_NOT_FOUND);
		}
		status.setResult("{\"id\":"+review.getId()+"}");
		status.write();
	}
	
	public void deleteReview(EventService delegate,HttpServletRequest request,HttpServletResponse response){
		Status status = new Status(request,response);
		int userId = ServerHelper.getUserId(request);
		int succ = 0;
		try {
			String content = IOUtil.getContent4InputStream(request.getInputStream());
			JSONObject json = JSONObject.fromObject(content);
			succ = delegate.deleteReview(json.getLong("eventId"), json.getInt("id"), userId);
			if(succ==0) status.setCode(HomiStatusCode.API_EXCEPTION);
		} catch (RecordNotFoundException e) {
			status.setCode(HomiStatusCode.RECORD_NOT_FOUND);
			logger.error(e.getMessage(), e);
		} catch (PermissionDeniedException e) {
			status.setCode(HomiStatusCode.PERMISSION_ERROR);
			logger.error(e.getMessage(), e);
		}catch (IOException e){
			status.setCode(HomiStatusCode.API_EXCEPTION);
			logger.error(e.getMessage(), e);
		}
		status.write();
	}
	
	public void listReview(EventService delegate,long eventId,int offset,int limit,
			HttpServletRequest request,HttpServletResponse response){
		Status status = new Status(request,response);
		List<Review> list = delegate.listReview(eventId, offset, limit);
		JSONArray result = new JSONArray();
		JSONObject json = null;
		User reviewer = null;
		User receiver = null;
		for(Review review : list){
			reviewer = userService.getUserById(review.getReviewer());
			receiver = userService.getUserById(review.getReceiver());
			json = JSONObject.fromObject(review);
			json.remove("tableName");
			json.put("receiverNickName", receiver==null?"无名":receiver.getNickName());
			json.put("reviewerNickName", reviewer==null?"无名":reviewer.getNickName());
			json.put("reviewerAvatar", reviewer==null?"":HomiUtil.getRealUrl(reviewer.getAvatar()));
			json.put("createAt", review.getCreateAt().getTime());
			result.add(json);
		}
		status.setResult(result);
		status.write();
	}
}
